﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using CloudClip.ExtensionMethod;
using System.ComponentModel;
using System.Reflection;
using ExtensionLibrary.Exception;
using System.Windows.Forms;

namespace CloudClip
{
    public class Setting
    {
        public string ClipFolderPath { get; set; }

        public decimal ClipSize { get; set; }

        public bool IsAutoPast { get; set; }

        public Int32 HotKey1 { get; set; }

        public Int32 HotKey2 { get; set; }

        public Int32 HotKey3 { get; set; }
    }


    public static class SettingHelper 
    {
       private static string _settingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "setting.xml");

        public static void Save(this Setting setting)
        {
            using (StreamWriter streamWriter = new StreamWriter(_settingPath))
            {
                streamWriter.Write(setting.ToXML());
            }
        }
        public static bool CheckSetting()
        {
            return _settingPath.CheckFileExist();
        }

        public static Setting Load()
        {
            Setting setting = new Setting(); 

            using (StreamReader streamReader = new StreamReader(_settingPath))
            {
                string sXML = streamReader.ReadToEnd();

                Setting xml = XMLExtension.FromXML<Setting>(sXML);

                foreach (PropertyInfo property in setting.GetType().GetProperties())
                {
                    object oValue = property.GetValue(xml, null);

                    //如果取不到值, 代表沒有預設值
                    if (oValue == null)
                    {
                        object[] attributes =
                            property.GetCustomAttributes(typeof(DefaultValueAttribute), false);

                        if (attributes.Count() != 0)
                        {
                            DefaultValueAttribute attribute = attributes[0] as DefaultValueAttribute;
                            property.SetValue(setting, attribute.Value, null);
                        }
                    }
                    else
                    {
                        property.SetValue(setting, oValue, null);
                    }
                }
            }

            return setting;
        }
    }
}
